package ginx

import (
	"gitee.com/dn-jinmin/authx"
	"github.com/gin-gonic/gin"
)

func AuthJwt(secret string) gin.HandlerFunc {
	tokenParser := authx.NewJWTValidator(secret)
	return func(c *gin.Context) {
		var err error
		defer func() {
			if err == nil {
				return
			}

			if ErrorResp != nil {
				ErrorResp(c, err)
			} else {
				c.Error(err)
			}
			c.Abort()
		}()

		r, err := tokenParser.Parse(c.Request)
		if err != nil {
			return
		}

		// 权限校验
		err = Authx.HaveAccessTo(r.Context(), authx.GetUId(r.Context()), c.Request.URL.Path, c.Request.Method)
		if err != nil {
			return
		}

		c.Request = r
		c.Next()
	}
}
